<?php

class set
{
	
	private static $settings;
	
	public static function init()
	{
		global $db;
		
		$query = 'SELECT `slug`, `group`, `value` FROM config ORDER BY `id`;';
		$result = $db->query($query);
		
		if (!$result || $db->numrows($result) == 0)
		{
			gerror_page(
				'Database Error', 
				'Could not fetch the configuration from the database.' . nn . 
				'<br />'
			);
			$db->free($result);
			return(false);
		}
		
		while ($data = $db->frow($result))
		{
			self::$settings[$data['slug']] = array($data['group'], unserialize($data['value']));
		}
		$db->free($result);
		return(true);
	}
	
	public static function get($key, $from_group = false)
	{
		if ($from_group == false)
		{
			if(isset(self::$settings[$key]))
			{
				return(self::$settings[$key][1]);
			}
		}
		else
		{
			$return = array();
			foreach(self::$settings as $slug => $data)
			{
				if ($data[0] == $key)
				{
					$return[$slug] = $data[1];
				}
			}
			return($return);
		}
		return(false);
	}
	
	public static function update($key, $val, $ckey = false)
	{
		global $db;
		
		if ($ckey == false)
		{
			if (isset(self::$settings[$key]) && self::$settings[$key][1] != $val)
			{
				$query = 'UPDATE config SET `value` = "' . $db->escape(serialize($val)) . '" WHERE `slug` = "' . $db->escape($key) . '";';
				$result = $db->query($query);
				if ($result)
				{
					self::$settings[$key][1] = $val;
					return(true);
				}
			}
		}
		else
		{
			$val = gen_slug($val, true);
			if (isset(self::$settings[$key]) && $key != $val)
			{
				$query = 'UPDATE config SET `slug` = "' . $db->escape($val) . '" WHERE `slug` = "' . $db->escape($key) . '";';
				$result = $db->query($query);
				if ($result)
				{
					self::$settings[$val] = self::$settings[$key];
					unset(self::$settings[$key]);
					return(true);
				}
			}
		}
		return(false);
	}
}

